package jdklearning.classloader.brokeparentdelegate;



/**
 * @author shenenlu 2021年07月16日 下午16:19:50
 */
public class MyClassLoader extends ClassLoader {


    public static void main(String[] args) throws ClassNotFoundException {
        // ServiceLoader.load()
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> aClass = myClassLoader.loadClass(Test1.class.getName());
        System.out.println(aClass.getClassLoader());
    }
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        System.out.println("My findClass!");
        return null;
    }

    protected Class<?> loadClass(String name, boolean resolve)
            throws ClassNotFoundException
    {
        synchronized (getClassLoadingLock(name)) {
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                long t0 = System.nanoTime();
                try {
                    //修改classloader的原双亲委派逻辑，从而打破双亲委派
                    if (name.startsWith("jdklearning.classloader.brokeparentdelegate")){
                        c=findClass(name);
                    }
                    else {
                        c = this.getParent().loadClass(name);
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

                if (c == null) {
                    long t1 = System.nanoTime();
                    c = findClass(name);
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }

}



class Test1 {

}